Ext.namespace("Microtraining.Admin.Lesson");
Mt = Microtraining.Admin;
Mt.Lesson={
  /**
   * 全局配置
   */
  Config:{
  /**
   *分页:每页显示记录数
   */
  PageSize:15,
  /**
   *显示配置
   */
  View:{
    /**
     * 显示课程的视图相对课程列表Grid的位置
     * 1:上方,2:下方,3:左侧,4:右侧,
     */
    Direction:2,
    /**
     *是否显示。
     */
    IsShow:0,
    /**
     * 是否固定显示课程信息页(或者打开新窗口)
     */
    IsFix:0
  }
  },
  /**
   * Cookie设置
   */
  Cookie:new Ext.state.CookieProvider(),
  /**
   * 初始化
   */
  Init:function(){
  if (Mt.Lesson.Cookie.get('View.Direction')){
    Mt.Lesson.Config.View.Direction=Mt.Lesson.Cookie.get('View.Direction');
  }
  if (Mt.Lesson.Cookie.get('View.IsFix')!=null){
    Mt.Lesson.Config.View.IsFix=Mt.Lesson.Cookie.get('View.IsFix');
  }
  }
};
/**
 * Model:数据模型
 */
Mt.Lesson.Store = {
  /**
   * 课程
   */
  lessonStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
          {name: 'lesson_id',type: 'int'},
          {name: 'company_id',type: 'int'},
          {name: 'company_name',type: 'string'},
          {name: 'admin_name',type: 'string'},
          {name: 'lesson_name',type: 'string'},
          {name: 'keywords',type: 'string'},
          {name: 'sort_order',type: 'int'},
          {name: 'head_image',type: 'string'},
          {name: 'isShow',type: 'string'},
          {name: 'memberStr',type: 'string'}
      ]}
  ),
  writer: new Ext.data.JsonWriter({
    encode: false
  }),
  listeners : {
    beforeload : function(store, options) {
    if (Ext.isReady) {
      if (!options.params.limit)options.params.limit=Mt.Lesson.Config.PageSize;
      Ext.apply(options.params, Mt.Lesson.View.Running.lessonGrid.filter);//保证分页也将查询条件带上
    }
    }
  }
  }),
  /**
   * 企业
   */
  companyStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/company.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'companys',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'company_id'
    }, [
      {name: 'company_id', mapping: 'company_id'},
      {name: 'company_name', mapping: 'company_name'}
    ])
  }),
  /**
   * 会员课程
   */
  mlessonStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'mlesson_id',type: 'int'},
        {name: 'lesson_name',type: 'string'},
        {name: 'username',type: 'string'} 
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Lesson.Config.PageSize;
          Ext.apply(options.params, Mt.Lesson.View.Running.mlessonGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  }),
  /**
   * 会员
   */
  selectMemberStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'member_id',type: 'int'},
        {name: 'company_id',type: 'int'},
        {name: 'company_name',type: 'string'},
        {name: 'department_id',type: 'int'},
        {name: 'department_name',type: 'string'},
        {name: 'position_id',type: 'int'},
        {name: 'position_name',type: 'string'},
        {name: 'area_id',type: 'int'},
        {name: 'area_name',type: 'string'},
        {name: 'username',type: 'string'},
        {name: 'password',type: 'string'},
        {name: 'realname',type: 'string'},
        {name: 'code',type: 'string'},
        {name: 'tel',type: 'string'},
        {name: 'email',type: 'string'},
        {name: 'qq',type: 'string'},
        {name: 'weixin',type: 'string'},
        {name: 'icon_image',type: 'string'},
        {name: 'point',type: 'float'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          Ext.apply(options.params, Mt.Lesson.View.Running.selectMemberWindow.memberGrid.filter);//保证分页也将查询条件带上
        }
      },
      load : function(records,options){
        if (records&&records.data&&records.data.items) {
          var selData  = Mt.Lesson.View.Running.selectMemberWindow.selData;//选中的会员
          var data     = records.data.items;
          //把已经推荐的会员选中
          var sm=Mt.Lesson.View.Running.selectMemberWindow.memberGrid.sm;
          var rows=Mt.Lesson.View.Running.selectMemberWindow.memberGrid.getView().getRows();
          for(var i=0;i<rows.length;i++){
            if(selData[data[i]['data'].member_id]){
              sm.selectRow(i, true);
            }
          }
        }
      }
    }
  }),
  /**
   * 企业
   */
  companyStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/company.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'companys',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'company_id'
    }, [
      {name: 'company_id', mapping: 'company_id'},
      {name: 'company_name', mapping: 'company_name'}
    ])
  }),
  /**
   * 部门
   */
  departmentStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/department.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'departments',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'department_id'
    }, [
      {name: 'department_id', mapping: 'department_id'},
      {name: 'department_name', mapping: 'department_name'}
    ])
  }),
  /**
   * 职位
   */
  positionStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/position.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'positions',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'position_id'
    }, [
      {name: 'position_id', mapping: 'position_id'},
      {name: 'position_name', mapping: 'position_name'}
    ])
  }),
  /**
   * 地区
   */
  areaStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/area.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'areas',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'area_id'
    }, [
      {name: 'area_id', mapping: 'area_id'},
      {name: 'area_name', mapping: 'area_name'}
    ])
  }),
  /**
   * 会员
   */
  memberStoreForCombo:new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
      url: 'home/admin/src/httpdata/member.php'
    }),
    reader: new Ext.data.JsonReader({
      root: 'members',
      autoLoad: true,
      totalProperty: 'totalCount',
      idProperty: 'member_id'
    }, [
      {name: 'member_id', mapping: 'member_id'},
      {name: 'username', mapping: 'username'}
    ])
  }),
  /**
   * 章节
   */
  chapterStore:new Ext.data.Store({
    reader: new Ext.data.JsonReader({
      totalProperty: 'totalCount',
      successProperty: 'success',
      root: 'data',remoteSort: true,
      fields : [
        {name: 'chapter_id',type: 'int'},
        {name: 'lesson_name',type: 'string'},
        {name: 'chapter_name',type: 'string'},
        {name: 'content',type: 'string'},
        {name: 'keywords',type: 'string'},
        {name: 'isShow',type: 'string'},
        {name: 'sort_order',type: 'int'},
        {name: 'begin_time',type: 'date',dateFormat:'Y-m-d H:i:s'},
        {name: 'end_time',type: 'date',dateFormat:'Y-m-d H:i:s'}
      ]}
    ),
    writer: new Ext.data.JsonWriter({
      encode: false 
    }),
    listeners : {
      beforeload : function(store, options) {
        if (Ext.isReady) {
          if (!options.params.limit)options.params.limit=Mt.Lesson.Config.PageSize;
          Ext.apply(options.params, Mt.Lesson.View.Running.chapterGrid.filter);//保证分页也将查询条件带上
        }
      }
    }
  })
};
/**
 * View:课程显示组件
 */
Mt.Lesson.View={
  /**
   * 编辑窗口：新建或者修改课程
   */
  EditWindow:Ext.extend(Ext.Window,{
  constructor : function(config) {
    config = Ext.apply({
    /**
     * 自定义类型:保存类型
     * 0:保存窗口,1:修改窗口
     */
    savetype:0,
    closeAction : "hide",
    constrainHeader:true,maximizable: true,collapsible: true,
    width : 450,height : 550,minWidth : 400,minHeight : 450,
    layout : 'fit',plain : true,buttonAlign : 'center',
    defaults : {
      autoScroll : true
    },
    listeners:{
      beforehide:function(){
      this.editForm.form.getEl().dom.reset();
      }
    },
    items : [
      new Ext.form.FormPanel({
      ref:'editForm',layout:'form',fileUpload: true,
      labelWidth : 100,labelAlign : "center",
      bodyStyle : 'padding:5px 5px 0',align : "center",
      api : {},
      defaults : {
        xtype : 'textfield',anchor:'98%'
      },
      items : [
              {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
              {xtype: 'hidden',  name : 'head_image',ref:'../head_image'},
              {fieldLabel : '课程名称',name : 'lesson_name'},
              {fieldLabel : '头像',name : 'head_imageUpload',ref:'../head_imageUpload',xtype:'fileuploadfield',
              emptyText: '请上传头像文件',buttonText: '',accept:'image/*',buttonCfg: {iconCls: 'upload-icon'}},
              {fieldLabel : '排序',name : 'sort_order',xtype : 'numberfield'},
              {fieldLabel : '是否显示',hiddenName : 'isShow'
                 ,xtype:'combo',ref:'../isShow',mode : 'local',triggerAction : 'all',
                 lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
                 store : new Ext.data.SimpleStore({
                   fields : ['value', 'text'],
                   data : [['0', '否'], ['1', '是']]
                 }),emptyText: '请选择是否显示',
                 valueField : 'value',displayField : 'text'
              }
      ]
      })
    ],
    buttons : [{
      text: "",ref : "../saveBtn",scope:this,
      handler : function() {

      if (!this.editForm.getForm().isValid()) {
        return;
      }
 
      editWindow=this;
      if (this.savetype==0){
        this.editForm.api.submit=ExtServiceLesson.save;
        this.editForm.getForm().submit({
        success : function(form, action) {
          Ext.Msg.alert("提示", "保存成功！");
          Mt.Lesson.View.Running.lessonGrid.doSelectLesson();
          form.reset();
          editWindow.hide();
        },
        failure : function(form, response) {
          Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
        }
        });
      }else{
        this.editForm.api.submit=ExtServiceLesson.update;
        this.editForm.getForm().submit({
        success : function(form, action) {
          Mt.Lesson.View.Running.lessonGrid.store.reload();
          Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
          Mt.Lesson.View.Running.lessonGrid.bottomToolbar.doRefresh();
          }});
          form.reset();
          editWindow.hide();
        },
        failure : function(form, response) {
          Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
        }
        });
      }
      }
    }, {
      text : "取 消",scope:this,
      handler : function() {
      this.hide();
      }
    }, {
      text : "重 置",ref:'../resetBtn',scope:this,
      handler : function() {
      this.editForm.form.loadRecord(Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected());
      this.head_imageUpload.setValue(this.head_image.getValue());
      }
    }]
    }, config);
    Mt.Lesson.View.EditWindow.superclass.constructor.call(this, config);
  }
  }),
  /**
   * 显示课程详情
   */
  LessonView:{
  /**
   * Tab页：容器包含显示与课程所有相关的信息
   */
  Tabs:Ext.extend(Ext.TabPanel,{
    constructor : function(config) {
    config = Ext.apply({
      region : 'south',collapseMode : 'mini',split : true,
      activeTab: 1, tabPosition:"bottom",resizeTabs : true,
      header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
      defaults : {
      autoScroll : true,
      layout:'fit'
      },
      listeners:{
      beforetabchange:function(tabs,newtab,currentTab){
        if (tabs.tabFix==newtab){
        if (Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected()==null){
          Ext.Msg.alert('提示', '请先选择课程！');
          return false;
        }
        Mt.Lesson.Config.View.IsShow=1;
        Mt.Lesson.View.Running.lessonGrid.showLesson();
        Mt.Lesson.View.Running.lessonGrid.tvpView.menu.mBind.setChecked(false);
        return false;
        }
      }
      },
      items: [
      {title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
      ]
    }, config);
    Mt.Lesson.View.LessonView.Tabs.superclass.constructor.call(this, config);
        Mt.Lesson.View.Running.mlessonGrid=new Mt.Lesson.View.MlessonView.Grid();
        Mt.Lesson.View.Running.chapterGrid=new Mt.Lesson.View.ChapterView.Grid();
    this.onAddItems();
    },
    /**
     * 根据布局调整Tabs的宽度或者高度以及折叠
     */
    enableCollapse:function(){
    if ((Mt.Lesson.Config.View.Direction==1)||(Mt.Lesson.Config.View.Direction==2)){
      this.width =Ext.getBody().getViewSize().width;
      this.height=Ext.getBody().getViewSize().height/2;
    }else{
      this.width =Ext.getBody().getViewSize().width/2;
      this.height=Ext.getBody().getViewSize().height;
    }
    this.ownerCt.setSize(this.width,this.height);
    if (this.ownerCt.collapsed)this.ownerCt.expand();
    this.ownerCt.collapsed=false;
    },
    onAddItems:function(){
    this.add(
      {title: '基本信息',ref:'tabLessonDetail',iconCls:'tabs',
       tpl: [
       '<table class="viewdoblock">',
             '  <tr class="entry"><td class="head">企业</td><td class="content">{company_name}</td></tr>',
             '  <tr class="entry"><td class="head">所属用户</td><td class="content">{admin_name}</td></tr>',
             '  <tr class="entry"><td class="head">课程名称</td><td class="content">{lesson_name}</td></tr>',
             '  <tr class="entry"><td class="head">图标路径</td><td class="content">{head_image}</td></tr>',
             '  <tr class="entry"><td class="head">图标</td><td class="content"><tpl if="head_image"><a href="upload/images/{head_image}" target="_blank"><img width="50px" height="50px" src="upload/images/{head_image}" /></a></tpl></td></tr>', 
             '  <tr class="entry"><td class="head">排序</td><td class="content">{sort_order}</td></tr>',
       '</table>'
       ]}
    );
        this.add(
          /*{title: '学习的会员',iconCls:'tabs',tabWidth:150,
           items:[Mt.Lesson.View.Running.mlessonGrid]
          },*/
          {title: '章节',iconCls:'tabs',tabWidth:150,
           items:[Mt.Lesson.View.Running.chapterGrid]
          }
        );
    }
  }),
  /**
   * 窗口:显示课程信息
   */
  Window:Ext.extend(Ext.Window,{
    constructor : function(config) {
    config = Ext.apply({
      title:"查看课程",constrainHeader:true,maximizable: true,minimizable : true,
      width : 705,height : 500,minWidth : 450,minHeight : 400,
      layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
      closeAction : "hide",
      items:[new Mt.Lesson.View.LessonView.Tabs({ref:'winTabs',tabPosition:'top'})],
      listeners: {
      minimize:function(w){
        w.hide();
        Mt.Lesson.Config.View.IsShow=0;
        Mt.Lesson.View.Running.lessonGrid.tvpView.menu.mBind.setChecked(true);
      },
      hide:function(w){
        Mt.Lesson.View.Running.lessonGrid.tvpView.toggle(false);
      }
      },
      buttons: [{
      text: '新增课程',scope:this,
      handler : function() {this.hide();Mt.Lesson.View.Running.lessonGrid.addLesson();}
      },{
      text: '修改课程',scope:this,
      handler : function() {this.hide();Mt.Lesson.View.Running.lessonGrid.updateLesson();}
      }]
    }, config);
    Mt.Lesson.View.LessonView.Window.superclass.constructor.call(this, config);
    }
  })
  },
  /**
   * 视图：会员
   */
  MemberView:{
    SelectMemberWindow:Ext.extend(Ext.Window,{
      constructor : function(config) {
        config = Ext.apply({
          selData:null,//选中的会员
          oldData:null,//已关联的会员
          title:"选择会员",updateData:null,closeAction:"hide",constrainHeader:true,maximizable:true,collapsible:true,
          width:720,minWidth:720,height:560,minHeight:450,layout:'fit',plain : true,buttonAlign : 'center',
          defaults : {autoScroll : true,},
          listeners:{
            beforehide:this.doHide
          },
          items : [new Mt.Lesson.View.MemberView.MemberGrid({ref:"memberGrid"})],
          buttons : [ {
            text: "确定",ref : "../saveBtn",scope:this,
            handler : function() {
              var selData = this.selData;
              var oldData = this.oldData;
              //课程标识
              // var lesson_id=Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected().data.lesson_id;

              var lesson_id  = Mt.Lesson.View.Running.selectMemberWindow.memberGrid.lesson_id; 

              var msg = lesson_id.length == 1 ? '确实要更改所选的课程吗?' : '课程多选模式下会员的课程将只保留所选课程，是否继续？';

              Ext.Msg.confirm('提示', msg, function(btn){
                if (btn == 'no') {
                  return false;
                }
                var condition={'selData':selData,"oldData":oldData,"lesson_id":lesson_id};
                Ext.Msg.show({
                  title: '请等待', msg: '操作进行中，请稍后...',
                  animEl: 'loading', icon: Ext.Msg.WARNING,
                  closable: true, progress: true, progressText: '', width: 300
                });
                ExtServiceLesson.updateLessonMember(condition,function(provider, response) {
                  if (response.result.success==true) {
                    var msg = "操作成功！";
                    if(response.result.del){
                      msg += "<font color=red>取消</font>了<font color=red>"+response.result.del+"</font>个关联会员,";
                    }
                    if(response.result.add){
                      msg += "<font color=green>添加</font>了<font color=green>"+response.result.add+"</font>个关联会员";
                    }
                    Ext.Msg.alert('提示', msg);
                  } else {
                    Mt.Lesson.Store.selectMemberStore.removeAll();
                    Ext.Msg.alert('提示', response.result.msg);
                  }
                  Mt.Lesson.View.Running.selectMemberWindow.hideWindow();
                  Mt.Lesson.View.Running.lessonGrid.doSelectLesson();
                });

              },this); 
              
            }
          }, {
            text : "取 消",scope:this,
            handler : function() {
              this.hide();
            }
          }]
        }, config);
        Mt.Lesson.View.MemberView.SelectMemberWindow.superclass.constructor.call(this, config);
      },
      /**
      * 根据选择的会员,改变标题
      */
      changeTitle: function(){
        var title   = "选择 会员";
        var selData = this.selData;
        var count   = this.objElCount(selData);
        if(count){
          title += "（已经选择了<font color=green>"+count+"</font>件会员）";
        }else{
          title += "（尚未选择任何会员）";
        }
        this.setTitle(title);
      },
      /**
      * 判断自定义对象元素个数
      */
      objElCount: function(obj){
        var count = 0;
        for(var n in obj){count++}
        return count;
      },
      /**
       * 确认取消图片处理
       * con:选择窗口
       */
      doHide: function (con) {
        //window初始化时会调用,此时con为null
        if(con){
          Ext.MessageBox.show({
            title:'提示',msg:'确定要取消么?<br /><font color=red>(所做操作将不会保存!)</font>',buttons:Ext.MessageBox.YESNO,icon:Ext.MessageBox.QUESTION,
            params:{con:con},
            fn:function(btn,text,opt) {
              if(btn=='yes') {
                con.hideWindow();
              }
            }
          });
          return false;
        }
      },
      /**
       * 隐藏窗口
       */
      hideWindow: function () {
        //移除beforehide事件，为了防止hide时进入死循环
        this.un('beforehide',this.doHide);
        this.hide();
        this.addListener('beforehide',this.doHide);
      }
    }),
    MemberGrid:Ext.extend(Ext.grid.GridPanel,{
      constructor : function(config) {
        config = Ext.apply({
          /**
           * 查询条件
           */
          filter:null,lesson_id:null,region : 'center',store : Mt.Lesson.Store.selectMemberStore,sm : this.sm,
          trackMouseOver : true,enableColumnMove : true,columnLines : true,loadMask : true,stripeRows : true,headerAsText : false,
          loadMask : {msg : '加载数据中，请稍候...'},
          defaults : {autoScroll : true},
          cm : new Ext.grid.ColumnModel({
            defaults:{width:120,sortable : true},
            columns : [
              this.sm,
              {header : '标识',dataIndex : 'member_id',hidden:true},
              {header : '用户名',dataIndex : 'username'},
              {header : '姓名',dataIndex : 'realname'},
              {header : '员工号',dataIndex : 'code'},
              {header : '公司',dataIndex : 'company_name'},
              {header : '部门',dataIndex : 'department_name'},
              {header : '职位',dataIndex : 'position_name'},
              {header : '地区',dataIndex : 'area_name'}
            ]
          }),
          tbar : {
            xtype : 'container',layout : 'anchor',
            height : 27,style:'font-size:14px',
            defaults : {
              height : 27,anchor : '100%'
            },
            items : [
              new Ext.Toolbar({
                enableOverflow: true,width : 80,ref:'menus',
                defaults : {
                  xtype : 'textfield',
                  listeners : {
                     specialkey : function(field, e) {
                      if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectMember();
                    }
                  }
                },
                items : [
                  {text: '全部',ref:'../../isSelect',xtype:'tbsplit',iconCls : 'icon-view',enableToggle: true,
                     toggleHandler:function(item, checked){
                      if (checked==true){
                        Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.menus.select.setChecked(true);
                      }else{
                        Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.menus.all.setChecked(true);
                      }
                    },
                    menu: {
                      items: [
                        {text: '全部',checked: true,group: 'isSelect',ref:'../../all',
                          checkHandler: function(item, checked){
                            if (checked){
                              Mt.Lesson.View.Running.selectMemberWindow.memberGrid.isSelect.setText(item.text);
                              Mt.Lesson.View.Running.selectMemberWindow.memberGrid.filter.selectType=0;
                            }
                            Mt.Lesson.View.Running.selectMemberWindow.memberGrid.doSelectMember();
                          }
                        },
                        {text: '未选择',checked: false,group: 'isSelect',ref:'../../unselect',
                            checkHandler: function(item, checked){
                              if (checked){
                                Mt.Lesson.View.Running.selectMemberWindow.memberGrid.isSelect.setText(item.text);
                                Mt.Lesson.View.Running.selectMemberWindow.memberGrid.filter.selectType=2;
                              }
                              Mt.Lesson.View.Running.selectMemberWindow.memberGrid.doSelectMember();
                            }
                        },
                        {text: '已选择',checked: false,group: 'isSelect',ref:'../../select',
                            checkHandler: function(item, checked){
                              if (checked){
                                Mt.Lesson.View.Running.selectMemberWindow.memberGrid.isSelect.setText(item.text);
                                Mt.Lesson.View.Running.selectMemberWindow.memberGrid.filter.selectType=1;
                              }
                              Mt.Lesson.View.Running.selectMemberWindow.memberGrid.doSelectMember();
                          }
                        }
                       ]
                    }
                  },
                  /*'公司','&nbsp;&nbsp;',{ref: '../mcompany_id',xtype: 'combo',
                     store:Mt.Lesson.Store.companyStoreForCombo,hiddenName : 'company_id',
                     emptyText: '请选择公司',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:280,pageSize:Mt.Lesson.Config.PageSize,
                     displayField:'company_name',valueField:'company_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{company_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',*/
                  '部门','&nbsp;&nbsp;',{ref: '../mdepartment_id',xtype: 'combo',
                     store:Mt.Lesson.Store.departmentStoreForCombo,hiddenName : 'department_id',
                     emptyText: '请选择部门',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:100,pageSize:Mt.Lesson.Config.PageSize,
                     displayField:'department_name',valueField:'department_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{department_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',
                  '职位','&nbsp;&nbsp;',{ref: '../mposition_id',xtype: 'combo',
                     store:Mt.Lesson.Store.positionStoreForCombo,hiddenName : 'position_id',
                     emptyText: '请选择职位',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:100,pageSize:Mt.Lesson.Config.PageSize,
                     displayField:'position_name',valueField:'position_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{position_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',
                  '地区','&nbsp;&nbsp;',{ref: '../marea_id',xtype: 'combo',
                     store:Mt.Lesson.Store.areaStoreForCombo,hiddenName : 'area_id',
                     emptyText: '请选择地区',itemSelector: 'div.search-item',
                     loadingText: '查询中...',width:100,pageSize:Mt.Lesson.Config.PageSize,
                     displayField:'area_name',valueField:'area_id',
                     mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                     forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                     tpl:new Ext.XTemplate(
                       '<tpl for="."><div class="search-item">',
                       '<h3>{area_name}</h3>',
                       '</div></tpl>'
                     )
                  },'&nbsp;&nbsp;',
                  '用户名','&nbsp;&nbsp;',{ref: '../musername',width:100},'&nbsp;&nbsp;',
                  {
                    xtype : 'button',text : '查询',scope: this,
                    handler : function() {
                      this.doSelectMember();
                    }
                  },
                  {
                    xtype : 'button',text : '重置',scope: this,
                    handler : function() {
                      // this.topToolbar.mcompany_id.setValue("");
                      this.topToolbar.mdepartment_id.setValue("");
                      this.topToolbar.mposition_id.setValue("");
                      this.topToolbar.marea_id.setValue("");
                      this.topToolbar.musername.setValue("");
                      this.filter={};
                      this.doSelectMember();
                    }
                  }
                ]
              })
            ]
          },
          bbar: new Ext.PagingToolbar({
            pageSize: Mt.Lesson.Config.PageSize,
            store: Mt.Lesson.Store.selectMemberStore,
            scope:this,autoShow:true,displayInfo: true,
            displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
            emptyMsg: "无显示数据",
            items: [
              {xtype:'label', text: '每页显示'},
              {xtype:'numberfield', value:Mt.Lesson.Config.PageSize,minValue:1,width:35,
                style:'text-align:center',allowBlank:false,
                listeners:
                {
                  change:function(Field, newValue, oldValue){
                    var num = parseInt(newValue);
                    if (isNaN(num) || !num || num<1)
                    {
                      num = Mt.Lesson.Config.PageSize;
                      Field.setValue(num);
                    }
                    Mt.Lesson.Config.PageSize = num;
                    this.ownerCt.ownerCt.doSelectMember();
                  },
                  specialKey :function(field,e){
                    if (e.getKey() == Ext.EventObject.ENTER){
                      var num = parseInt(field.getValue());
                      if (isNaN(num) || !num || num<1)
                      {
                        num = Mt.Lesson.Config.PageSize;
                      }
                      Mt.Lesson.Config.PageSize = num;
                      this.ownerCt.ownerCt.doSelectMember();
                    }
                  }
                }
              },
              {xtype:'label', text: '个'}
            ]
          })
        }, config);
        //初始化显示会员列表
        //this.doSelectMember();
        Mt.Lesson.Store.selectMemberStore.proxy=new Ext.data.DirectProxy({
          api: {read:ExtServiceLesson.queryPageLessonMember}
        });
        Mt.Lesson.View.MemberView.MemberGrid.superclass.constructor.call(this, config);
      },
      /**
      * SelectionModel
      */
      sm : new Ext.grid.CheckboxSelectionModel({
        listeners : {
          selectionchange:function(sm) {
            Mt.Lesson.View.Running.selectMemberWindow.changeTitle();
            Mt.Lesson.View.Running.selectMemberWindow.memberGrid.changeFilter();
          },
          rowselect: function(sm, rowIndex, record) {
            var selMemberWin  = Mt.Lesson.View.Running.selectMemberWindow;
            var selData    = selMemberWin.selData;
            var oldData    = selMemberWin.oldData;
            var member_id   = record.data.member_id;
            //添加该货品ID
            selData[member_id] = true;
            //判断是否是已关联的货品
            if(oldData[member_id]){
              oldData[member_id].active = true;
            }
          },
          rowdeselect: function(sm, rowIndex, record) {
            var selMemberWin  = Mt.Lesson.View.Running.selectMemberWindow;
            var selData    = selMemberWin.selData;
            var oldData    = selMemberWin.oldData;
            var member_id   = record.data.member_id;
            //删除该货品ID
            delete selData[member_id];
            //判断是否是已关联的货品
            if(oldData[member_id]){
              oldData[member_id].active = false;
            }
          }
        }
      }),
      doSelectMember : function() {
        var tmp_selMember =  this.filter.selMember ? '' : this.filter.selMember;
        var selectType = !this.filter.selectType ? '' : this.filter.selectType;
        var lesson_id=this.lesson_id;

        if (selectType != 0 && lesson_id.length > 1) {
          Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.menus.all.setChecked(true);
          Ext.Msg.alert('提示', '选择多个课程时 不能使用已选择和未选择');
          return;
        }
        if (this.topToolbar){

          if (!this.filter.selectType)this.filter.selectType=0;
          
          var mdepartment_id = this.topToolbar.mdepartment_id.getValue();
          var mposition_id = this.topToolbar.mposition_id.getValue();
          var marea_id = this.topToolbar.marea_id.getValue();
          var musername = this.topToolbar.musername.getValue();

          this.filter ={'department_id':mdepartment_id,'position_id':mposition_id,'area_id':marea_id,'username':musername,'lesson_id':lesson_id,'selectType':selectType};
        }

        this.filter.selMember=tmp_selMember;
        var condition = {'start':0,'limit':Mt.Lesson.Config.PageSize};
        Ext.apply(condition,this.filter);
        ExtServiceLesson.queryPageLessonMember(condition,function(provider, response) {
          if (response.result&&response.result.data) {
            var result       = new Array();
            result['data']     =response.result.data;
            result['totalCount'] =response.result.totalCount;
            Mt.Lesson.Store.selectMemberStore.loadData(result);
          } else {
            Mt.Lesson.Store.selectMemberStore.removeAll();
            Ext.Msg.alert('提示', '无符合条件的会员！');
          }
        });
      },
      /**
      * 修改查询条件
      */
      changeFilter: function(){
        var selData =Mt.Lesson.View.Running.selectMemberWindow.selData;
        var selArr  = new Array();
        for(var x in selData){
          selArr.push(x);
        }
        this.filter.selMember = selArr.join(",");
      }
    }),
  },
  /**
   * 视图：会员课程列表
   */
  MlessonView:{
  /**
   *  当前创建的会员课程编辑窗口
   */
  edit_window:null,
  /**
   * 编辑窗口：新建或者修改会员课程
   */
  EditWindow:Ext.extend(Ext.Window,{
    constructor : function(config) {
    config = Ext.apply({
      /**
       * 自定义类型:保存类型
       * 0:保存窗口,1:修改窗口
       */
      savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
      width : 450,height : 550,minWidth : 400,minHeight : 450,
      layout : 'fit',plain : true,buttonAlign : 'center',
      defaults : {autoScroll : true},
      listeners:{
      beforehide:function(){
        this.editForm.form.getEl().dom.reset();
      }
      },
      items : [
      new Ext.form.FormPanel({
        ref:'editForm',layout:'form',
        labelWidth : 100,labelAlign : "center",
        bodyStyle : 'padding:5px 5px 0',align : "center",
        api : {},
        defaults : {
        xtype : 'textfield',anchor:'98%'
        },
        items : [
                {xtype: 'hidden',name : 'mlesson_id',ref:'../mlesson_id'},
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                {xtype: 'hidden',name : 'member_id',ref:'../member_id'},
                {
                   fieldLabel : '用户',xtype: 'combo',name : 'username',ref : '../username',
                   store:Mt.Lesson.Store.memberStoreForCombo,emptyText: '请选择用户',itemSelector: 'div.search-item',
                   loadingText: '查询中...',width: 570, pageSize:Mt.Lesson.Config.PageSize,
                   displayField:'username',grid:this,
                   mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                     '<tpl for="."><div class="search-item">',
                       '<h3>{username}</h3>',
                     '</div></tpl>'
                   ),
                   listeners:{
                     'beforequery': function(event){delete event.combo.lastQuery;}
                   },
                   onSelect:function(record,index){
                     if(this.fireEvent('beforeselect', this, record, index) !== false){
                      this.grid.member_id.setValue(record.data.member_id);
                      this.grid.username.setValue(record.data.username);
                      this.collapse();
                     }
                   }
                } 
        ]
      })
      ],
      buttons : [{
      text: "",ref : "../saveBtn",scope:this,
      handler : function() {

        if (!this.editForm.getForm().isValid()) {
        return;
        }
        editWindow=this;
        if (this.savetype==0){
        this.editForm.api.submit=ExtServiceMlesson.save;
        this.editForm.getForm().submit({
          success : function(form, action) {
          Ext.Msg.alert("提示", "保存成功！");
          Mt.Lesson.View.Running.mlessonGrid.doSelectMlesson();
          form.reset();
          editWindow.hide();
          },
          failure : function(form, response) {
          Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
          }
        });
        }else{
        this.editForm.api.submit=ExtServiceMlesson.update;
        this.editForm.getForm().submit({
          success : function(form, action) {
          Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
            Mt.Lesson.View.Running.mlessonGrid.bottomToolbar.doRefresh();
          }});
          form.reset();
          editWindow.hide();
          },
          failure : function(form, response) {
          Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
          }
        });
        }
      }
      }, {
      text : "取 消",scope:this,
      handler : function() {
        this.hide();
      }
      }, {
      text : "重 置",ref:'../resetBtn',scope:this,
      handler : function() {
        this.editForm.form.loadRecord(Mt.Lesson.View.Running.mlessonGrid.getSelectionModel().getSelected());

      }
      }]
    }, config);
    Mt.Lesson.View.MlessonView.EditWindow.superclass.constructor.call(this, config);
    }
  }),
  /**
   * 查询条件
   */
  filter:null,
  /**
   * 视图：会员课程列表
   */
  Grid:Ext.extend(Ext.grid.GridPanel, {
    constructor : function(config) {
    config = Ext.apply({
      store : Mt.Lesson.Store.mlessonStore,sm : this.sm,
      frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
      loadMask : true,stripeRows : true,headerAsText : false,
      defaults : {autoScroll : true},
      cm : new Ext.grid.ColumnModel({
      defaults:{
        width:120,sortable : true
      },
      columns : [
              this.sm,
              {header : '标识',dataIndex : 'mlesson_id',hidden:true},
              {header : '用户',dataIndex : 'username'} 
      ]
      }),
      tbar : {
      xtype : 'container',layout : 'anchor',
      height : 27,style:'font-size:14px',
      defaults : {
        height : 27,anchor : '100%'
      },
      items : [
        new Ext.Toolbar({
        defaults:{
          scope: this
        },
        items : [
          {
          text: '反选',iconCls : 'icon-reverse',
          handler: function(){
            this.onReverseSelect();
          }
          },'-',{
          text : '添加学习的会员',iconCls : 'icon-add',
          handler : function() {
            this.addMlesson();
          }
          },'-',{
          text : '修改添加学习的会员',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
          handler : function() {
            this.updateMlesson();
          }
          },'-',{
          text : '删除添加学习的会员', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
          handler : function() {
            this.deleteMlesson();
          }
          },'-']}
      )]
      },
      bbar: new Ext.PagingToolbar({
      pageSize: Mt.Lesson.Config.PageSize,
      store: Mt.Lesson.Store.mlessonStore,scope:this,autoShow:true,displayInfo: true,
      displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
      items: [
        {xtype:'label', text: '每页显示'},
        {xtype:'numberfield', value:Mt.Lesson.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
        listeners:
        {
          change:function(Field, newValue, oldValue){
          var num = parseInt(newValue);
          if (isNaN(num) || !num || num<1)
          {
            num = Mt.Lesson.Config.PageSize;
            Field.setValue(num);
          }
          this.ownerCt.pageSize= num;
          Mt.Lesson.Config.PageSize = num;
          this.ownerCt.ownerCt.doSelectMlesson();
          },
          specialKey :function(field,e){
          if (e.getKey() == Ext.EventObject.ENTER){
            var num = parseInt(field.getValue());
            if (isNaN(num) || !num || num<1)num = Mt.Lesson.Config.PageSize;
            this.ownerCt.pageSize= num;
            Mt.Lesson.Config.PageSize = num;
            this.ownerCt.ownerCt.doSelectMlesson();
          }
          }
        }
        },{xtype:'label', text: '个'}
      ]
      })
    }, config);
    /**
     * 会员课程数据模型获取数据Direct调用
     */
    Mt.Lesson.Store.mlessonStore.proxy=new Ext.data.DirectProxy({
      api: {read:ExtServiceMlesson.queryPageMlesson}
    });
    Mt.Lesson.View.MlessonView.Grid.superclass.constructor.call(this, config);
    },
    /**
     * 行选择器
     */
    sm : new Ext.grid.CheckboxSelectionModel({
    listeners : {
      selectionchange:function(sm) {
      // 判断删除和更新按钮是否可以激活
      this.grid.btnRemove.setDisabled(sm.getCount() < 1);
      this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
      }
    }
    }),
    /**
     * 查询符合条件的会员课程
     */
    doSelectMlesson : function() {
    if (Mt.Lesson.View.Running.lessonGrid&&Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected()){
      var lesson_id = Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected().data.lesson_id;
      var condition = {'lesson_id':lesson_id,'start':0,'limit':Mt.Lesson.Config.PageSize};
      this.filter     ={'lesson_id':lesson_id};
      ExtServiceMlesson.queryPageMlesson(condition,function(provider, response) {
      if (response.result){
        if (response.result.data) {
        var result       = new Array();
        result['data']     =response.result.data;
        result['totalCount'] =response.result.totalCount;
        Mt.Lesson.Store.mlessonStore.loadData(result);
        } else {
        Mt.Lesson.Store.mlessonStore.removeAll();
        Ext.Msg.alert('提示', '无符合条件的会员课程！');
        }

        if (Mt.Lesson.Store.mlessonStore.getTotalCount()>Mt.Lesson.Config.PageSize){
         Mt.Lesson.View.Running.mlessonGrid.bottomToolbar.show();
        }else{
         Mt.Lesson.View.Running.mlessonGrid.bottomToolbar.hide();
        }
        Mt.Lesson.View.Running.lessonGrid.ownerCt.doLayout();
      }
      });
    }
    },
    /**
     * 反选
     */
    onReverseSelect:function() {
    for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
      if (this.sm.isSelected(i)) {
      this.sm.deselectRow(i);
      }else {
      this.sm.selectRow(i, true);
      }
    }
    },
    /**
     * 新建会员课程
     */
    addMlesson : function(){
    if (Mt.Lesson.View.MlessonView.edit_window==null){
      Mt.Lesson.View.MlessonView.edit_window=new Mt.Lesson.View.MlessonView.EditWindow();
    }
    Mt.Lesson.View.MlessonView.edit_window.resetBtn.setVisible(false);
    Mt.Lesson.View.MlessonView.edit_window.saveBtn.setText('保 存');
    Mt.Lesson.View.MlessonView.edit_window.setTitle('添加会员课程');
    Mt.Lesson.View.MlessonView.edit_window.savetype=0;
    Mt.Lesson.View.MlessonView.edit_window.mlesson_id.setValue("");
    var company_id = Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected().data.lesson_id;
    Mt.Lesson.View.MlessonView.edit_window.lesson_id.setValue(company_id);

    Mt.Lesson.View.MlessonView.edit_window.show();
    Mt.Lesson.View.MlessonView.edit_window.maximize();
    },
    /**
     * 编辑会员课程时先获得选中的会员课程信息
     */
    updateMlesson : function() {
    if (Mt.Lesson.View.MlessonView.edit_window==null){
      Mt.Lesson.View.MlessonView.edit_window=new Mt.Lesson.View.MlessonView.EditWindow();
    }
    Mt.Lesson.View.MlessonView.edit_window.saveBtn.setText('修 改');
    Mt.Lesson.View.MlessonView.edit_window.resetBtn.setVisible(true);
    Mt.Lesson.View.MlessonView.edit_window.setTitle('修改会员课程');
    Mt.Lesson.View.MlessonView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
    Mt.Lesson.View.MlessonView.edit_window.savetype=1;

    Mt.Lesson.View.MlessonView.edit_window.show();
    Mt.Lesson.View.MlessonView.edit_window.maximize();
    },
    /**
     * 删除会员课程
     */
    deleteMlesson : function() {
    Ext.Msg.confirm('提示', '确实要删除所选的会员课程吗?', this.confirmDeleteMlesson,this);
    },
    /**
     * 确认删除会员课程
     */
    confirmDeleteMlesson : function(btn) {
    if (btn == 'yes') {
      var del_mlesson_ids ="";
      var selectedRows  = this.getSelectionModel().getSelections();
      for ( var flag = 0; flag < selectedRows.length; flag++) {
      del_mlesson_ids=del_mlesson_ids+selectedRows[flag].data.mlesson_id+",";
      }
      ExtServiceMlesson.deleteByIds(del_mlesson_ids);
      this.doSelectMlesson();
      Ext.Msg.alert("提示", "删除成功！");
    }
    }
  })
  },
  /**
   * 视图：章节列表
   */
  ChapterView:{
  /**
   *  当前创建的章节编辑窗口
   */
  edit_window:null,
  /**
   * 编辑窗口：新建或者修改章节
   */
  EditWindow:Ext.extend(Ext.Window,{
    constructor : function(config) {
    config = Ext.apply({
      /**
       * 自定义类型:保存类型
       * 0:保存窗口,1:修改窗口
       */
      savetype:0,closeAction : "hide",constrainHeader:true,maximizable: true,collapsible: true,
      width : 450,height : 550,minWidth : 400,minHeight : 450,
      layout : 'fit',plain : true,buttonAlign : 'center',
      defaults : {autoScroll : true},
      listeners:{
        beforehide:function(){
          this.editForm.form.getEl().dom.reset();
        },
        afterrender:function(){
          switch (Mt.Lesson.Config.OnlineEditor)
          {
              case 1:
                  ckeditor_replace_content();
                  break
              case 2:
                  Mt.Chapter.View.EditWindow.KindEditor_content = KindEditor.create('textarea[name="content"]',{width:'98%',minHeith:'350px', filterMode:true});
                  break
              case 3:
                  pageInit_content();
                  break
              default:
                  this.editForm.content.setWidth("98%");
                  pageInit_ue_content();
          }
        }
      },
      items : [
      new Ext.form.FormPanel({
        ref:'editForm',layout:'form',
        labelWidth : 100,labelAlign : "center",
        bodyStyle : 'padding:5px 5px 0',align : "center",
        api : {},
        defaults : {
        xtype : 'textfield',anchor:'98%'
        },
        items : [
                {xtype: 'hidden',name : 'chapter_id',ref:'../chapter_id'},
                {xtype: 'hidden',name : 'lesson_id',ref:'../lesson_id'},
                {fieldLabel : '章节名称',name : 'chapter_name'},
                {fieldLabel : '开始日期',ref:'../begin_time',name : 'begin_time',xtype : 'datefield',format : "Y-m-d"},
                {fieldLabel : '结束日期',ref:'../end_time',name : 'end_time',xtype : 'datefield',format : "Y-m-d"},
                {fieldLabel : '章节内容',name : 'content',xtype : 'textarea',id:'content',ref:'content'},
                // {fieldLabel : '内容关键字',name : 'keywords'},
                {fieldLabel : '是否显示',hiddenName : 'isShow'
                   ,xtype:'combo',ref:'../isShow',mode : 'local',triggerAction : 'all',
                   lazyRender : true,editable: false,allowBlank : false,valueNotFoundText:'否',
                   store : new Ext.data.SimpleStore({
                     fields : ['value', 'text'],
                     data : [['0', '否'], ['1', '是']]
                   }),emptyText: '请选择是否显示',
                   valueField : 'value',displayField : 'text'
                },
                {fieldLabel : '排序',name : 'sort_order',xtype : 'numberfield'}
        ]
      })
      ],
      buttons : [{
      text: "",ref : "../saveBtn",scope:this,
      handler : function() {
        switch (Mt.Lesson.Config.OnlineEditor)
        {
            case 1:
                if (CKEDITOR.instances.content) this.editForm.content.setValue(CKEDITOR.instances.content.getData());
                break
            case 2:
                if (Mt.Chapter.View.EditWindow.KindEditor_content)this.editForm.content.setValue(Mt.Chapter.View.EditWindow.KindEditor_content.html());
                break
            case 3:
                if (xhEditor_content)this.editForm.content.setValue(xhEditor_content.getSource());
                break
            default:
                if (ue_content)this.editForm.content.setValue(ue_content.getContent());
        }

        if (!this.editForm.getForm().isValid()) {
          return;
        }
        editWindow=this;
        if (this.savetype==0){
        this.editForm.api.submit=ExtServiceChapter.save;
        this.editForm.getForm().submit({
          success : function(form, action) {
          Ext.Msg.alert("提示", "保存成功！");
          Mt.Lesson.View.Running.chapterGrid.doSelectChapter();
          form.reset();
          editWindow.hide();
          },
          failure : function(form, response) {
          Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
          }
        });
        }else{
        this.editForm.api.submit=ExtServiceChapter.update;
        this.editForm.getForm().submit({
          success : function(form, action) {
          Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
            Mt.Lesson.View.Running.chapterGrid.bottomToolbar.doRefresh();
          }});
          form.reset();
          editWindow.hide();
          },
          failure : function(form, response) {
          Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
          }
        });
        }
      }
      }, {
      text : "取 消",scope:this,
      handler : function() {
        this.hide();
      }
      }, {
      text : "重 置",ref:'../resetBtn',scope:this,
      handler : function() {
        this.editForm.form.loadRecord(Mt.Lesson.View.Running.chapterGrid.getSelectionModel().getSelected());
        switch (Mt.Lesson.Config.OnlineEditor)
        {
            case 1:
                if (CKEDITOR.instances.content) CKEDITOR.instances.content.setData(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
                break
            case 2:
                if (Mt.Chapter.View.EditWindow.KindEditor_content) Mt.Chapter.View.EditWindow.KindEditor_content.html(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
                break
            case 3:
                if (xhEditor_content) xhEditor_content.setSource(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
                break
            default:
                if (ue_content) ue_content.setContent(Mt.Chapter.View.Running.chapterGrid.getSelectionModel().getSelected().data.content);
        }

      }
      }]
    }, config);
    Mt.Lesson.View.ChapterView.EditWindow.superclass.constructor.call(this, config);
    }
  }),
  /**
   * 查询条件
   */
  filter:null,
  /**
   * 视图：章节列表
   */
  Grid:Ext.extend(Ext.grid.GridPanel, {
    constructor : function(config) {
    config = Ext.apply({
      store : Mt.Lesson.Store.chapterStore,sm : this.sm,
      frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
      loadMask : true,stripeRows : true,headerAsText : false,
      defaults : {autoScroll : true},
      cm : new Ext.grid.ColumnModel({
      defaults:{
        width:120,sortable : true
      },
      columns : [
              this.sm,
              {header : '标识',dataIndex : 'chapter_id',hidden:true},
              {header : '章节名称',dataIndex : 'chapter_name'},
              {header : '开始时间',dataIndex : 'begin_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
              {header : '结束时间',dataIndex : 'end_time',renderer:Ext.util.Format.dateRenderer('Y-m-d')},
              // {header : '章节内容',dataIndex : 'content'},
              // {header : '内容关键字',dataIndex : 'keywords'},
              {header : '是否显示',dataIndex : 'isShow',renderer:function(value){if (value == true) {return "是";}else{return "否";}}},
              {header : '排序',dataIndex : 'sort_order'}
      ]
      }),
      tbar : {
      xtype : 'container',layout : 'anchor',
      height : 27,style:'font-size:14px',
      defaults : {
        height : 27,anchor : '100%'
      },
      items : [
        new Ext.Toolbar({
        defaults:{
          scope: this
        },
        items : [
          {
          text: '反选',iconCls : 'icon-reverse',
          handler: function(){
            this.onReverseSelect();
          }
          },'-',{
          text : '添加章节',iconCls : 'icon-add',
          handler : function() {
            this.addChapter();
          }
          },'-',{
          text : '修改章节',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
          handler : function() {
            this.updateChapter();
          }
          },'-',{
          text : '删除章节', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
          handler : function() {
            this.deleteChapter();
          }
          },'-']}
      )]
      },
      bbar: new Ext.PagingToolbar({
      pageSize: Mt.Lesson.Config.PageSize,
      store: Mt.Lesson.Store.chapterStore,scope:this,autoShow:true,displayInfo: true,
      displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',emptyMsg: "无显示数据",
      items: [
        {xtype:'label', text: '每页显示'},
        {xtype:'numberfield', value:Mt.Lesson.Config.PageSize,minValue:1,width:35,style:'text-align:center',allowBlank: false,
        listeners:
        {
          change:function(Field, newValue, oldValue){
          var num = parseInt(newValue);
          if (isNaN(num) || !num || num<1)
          {
            num = Mt.Lesson.Config.PageSize;
            Field.setValue(num);
          }
          this.ownerCt.pageSize= num;
          Mt.Lesson.Config.PageSize = num;
          this.ownerCt.ownerCt.doSelectChapter();
          },
          specialKey :function(field,e){
          if (e.getKey() == Ext.EventObject.ENTER){
            var num = parseInt(field.getValue());
            if (isNaN(num) || !num || num<1)num = Mt.Lesson.Config.PageSize;
            this.ownerCt.pageSize= num;
            Mt.Lesson.Config.PageSize = num;
            this.ownerCt.ownerCt.doSelectChapter();
          }
          }
        }
        },{xtype:'label', text: '个'}
      ]
      })
    }, config);
    /**
     * 章节数据模型获取数据Direct调用
     */
    Mt.Lesson.Store.chapterStore.proxy=new Ext.data.DirectProxy({
      api: {read:ExtServiceChapter.queryPageChapter}
    });
    Mt.Lesson.View.ChapterView.Grid.superclass.constructor.call(this, config);
    },
    /**
     * 行选择器
     */
    sm : new Ext.grid.CheckboxSelectionModel({
    listeners : {
      selectionchange:function(sm) {
      // 判断删除和更新按钮是否可以激活
      this.grid.btnRemove.setDisabled(sm.getCount() < 1);
      this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
      }
    }
    }),
    /**
     * 查询符合条件的章节
     */
    doSelectChapter : function() {
    if (Mt.Lesson.View.Running.lessonGrid&&Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected()){
      var lesson_id = Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected().data.lesson_id;
      var condition = {'lesson_id':lesson_id,'start':0,'limit':Mt.Lesson.Config.PageSize};
      this.filter     ={'lesson_id':lesson_id};
      ExtServiceChapter.queryPageChapter(condition,function(provider, response) {
      if (response.result){
        if (response.result.data) {
        var result       = new Array();
        result['data']     =response.result.data;
        result['totalCount'] =response.result.totalCount;
        Mt.Lesson.Store.chapterStore.loadData(result);
        } else {
        Mt.Lesson.Store.chapterStore.removeAll();
        Ext.Msg.alert('提示', '无符合条件的章节！');
        }

        if (Mt.Lesson.Store.chapterStore.getTotalCount()>Mt.Lesson.Config.PageSize){
         Mt.Lesson.View.Running.chapterGrid.bottomToolbar.show();
        }else{
         Mt.Lesson.View.Running.chapterGrid.bottomToolbar.hide();
        }
        Mt.Lesson.View.Running.lessonGrid.ownerCt.doLayout();
      }
      });
    }
    },
    /**
     * 反选
     */
    onReverseSelect:function() {
    for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
      if (this.sm.isSelected(i)) {
      this.sm.deselectRow(i);
      }else {
      this.sm.selectRow(i, true);
      }
    }
    },
    /**
     * 新建章节
     */
    addChapter : function(){
    if (Mt.Lesson.View.ChapterView.edit_window==null){
      Mt.Lesson.View.ChapterView.edit_window=new Mt.Lesson.View.ChapterView.EditWindow();
    }
    Mt.Lesson.View.ChapterView.edit_window.resetBtn.setVisible(false);
    Mt.Lesson.View.ChapterView.edit_window.saveBtn.setText('保 存');
    Mt.Lesson.View.ChapterView.edit_window.setTitle('添加章节');
    Mt.Lesson.View.ChapterView.edit_window.savetype=0;
    Mt.Lesson.View.ChapterView.edit_window.chapter_id.setValue("");
    var company_id = Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelected().data.lesson_id;
    Mt.Lesson.View.ChapterView.edit_window.lesson_id.setValue(company_id);
    switch (Mt.Lesson.Config.OnlineEditor)
    {
        case 1:
            if (CKEDITOR.instances.content) CKEDITOR.instances.content.setData("");
            break
        case 2:
            if (Mt.Chapter.View.EditWindow.KindEditor_content) Mt.Chapter.View.EditWindow.KindEditor_content.html("");
            break
        case 3:
            break
        default:
            if (ue_content)ue_content.setContent("");
    }

    Mt.Lesson.View.ChapterView.edit_window.show();
    Mt.Lesson.View.ChapterView.edit_window.maximize();
    },
    /**
     * 编辑章节时先获得选中的章节信息
     */
    updateChapter : function() {
    if (Mt.Lesson.View.ChapterView.edit_window==null){
      Mt.Lesson.View.ChapterView.edit_window=new Mt.Lesson.View.ChapterView.EditWindow();
    }
    Mt.Lesson.View.ChapterView.edit_window.saveBtn.setText('修 改');
    Mt.Lesson.View.ChapterView.edit_window.resetBtn.setVisible(true);
    Mt.Lesson.View.ChapterView.edit_window.setTitle('修改章节');
    Mt.Lesson.View.ChapterView.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
    Mt.Lesson.View.ChapterView.edit_window.savetype=1;
    switch (Mt.Lesson.Config.OnlineEditor)
    {
        case 1:
            if (CKEDITOR.instances.content) CKEDITOR.instances.content.setData(this.getSelectionModel().getSelected().data.content);
            break
        case 2:
            if (Mt.Chapter.View.EditWindow.KindEditor_content) Mt.Chapter.View.EditWindow.KindEditor_content.html(this.getSelectionModel().getSelected().data.content);
            break
        case 3:
            if (xhEditor_content)xhEditor_content.setSource(this.getSelectionModel().getSelected().data.content);
            break
        default:
            if (ue_content)ue_content.setContent(this.getSelectionModel().getSelected().data.content);
    }

    Mt.Lesson.View.ChapterView.edit_window.show();
    Mt.Lesson.View.ChapterView.edit_window.maximize();
    },
    /**
     * 删除章节
     */
    deleteChapter : function() {
    Ext.Msg.confirm('提示', '确实要删除所选的章节吗?', this.confirmDeleteChapter,this);
    },
    /**
     * 确认删除章节
     */
    confirmDeleteChapter : function(btn) {
    if (btn == 'yes') {
      var del_chapter_ids ="";
      var selectedRows  = this.getSelectionModel().getSelections();
      for ( var flag = 0; flag < selectedRows.length; flag++) {
      del_chapter_ids=del_chapter_ids+selectedRows[flag].data.chapter_id+",";
      }
      ExtServiceChapter.deleteByIds(del_chapter_ids);
      this.doSelectChapter();
      Ext.Msg.alert("提示", "删除成功！");
    }
    }
  })
  },
  /**
   * 窗口：批量上传课程
   */
  UploadWindow:Ext.extend(Ext.Window,{
  constructor : function(config) {
    config = Ext.apply({
    title : '批量上传课程数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
    layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
    items : [
      new Ext.form.FormPanel({
      ref:'uploadForm',fileUpload: true,
      width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
      frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
      defaults: {
        anchor: '95%',allowBlank: false,msgTarget: 'side'
      },
      items : [{
        xtype : 'fileuploadfield',
        fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
        emptyText: '请上传课程Excel文件',buttonText: '',
        accept:'application/vnd.ms-excel',
        buttonCfg: {iconCls: 'upload-icon'}
      }]
      })
    ],
    buttons : [{
      text : '上 传',
      scope:this,
      handler : function() {
        uploadWindow       =this;
        validationExpression   =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
        var isValidExcelFormat = new RegExp(validationExpression);
        var result       = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
        if (!result){
        Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
        return;
        }
        if (this.uploadForm.getForm().isValid()) {
        Ext.Msg.show({
          title : '请等待',msg : '文件正在上传中，请稍后...',
          animEl : 'loading',icon : Ext.Msg.WARNING,
          closable : true,progress : true,progressText : '',width : 300
        });
        this.uploadForm.getForm().submit({
          url : 'index.php?go=admin.upload.uploadLesson',
          success : function(form, response) {
          Ext.Msg.alert('成功', '上传成功');
          uploadWindow.hide();
          uploadWindow.uploadForm.upload_file.setValue('');
          Mt.Lesson.View.Running.lessonGrid.doSelectLesson();
          },
          failure : function(form, response) {
          Ext.Msg.alert('错误', response.result.data);
          }
        });
        }
      }
      },{
      text : '取 消',
      scope:this,
      handler : function() {
        this.uploadForm.upload_file.setValue('');
        this.hide();
      }
      }]
    }, config);
    Mt.Lesson.View.UploadWindow.superclass.constructor.call(this, config);
  }
  }),
  /**
   * 视图：课程列表
   */
  Grid:Ext.extend(Ext.grid.GridPanel, {
  constructor : function(config) {
    config = Ext.apply({
    /**
     * 查询条件
     */
    filter:null,
    region : 'center',
    store : Mt.Lesson.Store.lessonStore,
    sm : this.sm,
    frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
    loadMask : true,stripeRows : true,headerAsText : false,
    defaults : {
      autoScroll : true
    },
    cm : new Ext.grid.ColumnModel({
      defaults:{
      width:120,sortable : true
      },
      columns : [
      this.sm,
            {header : '标识',dataIndex : 'lesson_id',hidden:true},
            {header : '企业',dataIndex : 'company_name',hidden:true},
            {header : '所属用户',dataIndex : 'admin_name'},
            {header : '课程名称',dataIndex : 'lesson_name',width:300}, 
            {header : '排序',dataIndex : 'sort_order'},
            {header : '是否显示',dataIndex : 'isShow',renderer:function(value){if (value == true) {return "是";}else{return "否";}}}
      ]
    }),
    tbar : {
      xtype : 'container',layout : 'anchor',height : 27 * 2,style:'font-size:14px',
      defaults : {
      height : 27,anchor : '100%'
      },
      items : [
      new Ext.Toolbar({
        enableOverflow: true,width : 100,
        defaults : {
        xtype : 'textfield',
        listeners : {
           specialkey : function(field, e) {
          if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectLesson();
          }
        }
        },
        items : [
                '课程名称','&nbsp;&nbsp;',{ref: '../llesson_name'},'&nbsp;&nbsp;',
        {
          xtype : 'button',text : '查询',scope: this,
          handler : function() {
          this.doSelectLesson();
          }
        },
        {
          xtype : 'button',text : '重置',scope: this,
          handler : function() {
                    this.topToolbar.llesson_name.setValue("");
          this.filter={};
          this.doSelectLesson();
          }
        }]
      }),
      new Ext.Toolbar({
        defaults:{scope: this},
        items : [
        {
          text: '反选',iconCls : 'icon-reverse',
          handler: function(){
          this.onReverseSelect();
          }
        },'-',{
          text : '添加课程',iconCls : 'icon-add',
          handler : function() {
          this.addLesson();
          }
        },'-',{
          text : '修改课程',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
          handler : function() {
          this.updateLesson();
          }
        },'-',{
          text : '删除课程', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
          handler : function() {
          this.deleteLesson();
          }
        },'-',{
          xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
          handler : function() {
          this.importLesson();
          }
          // ,
          // menu: {
          // xtype:'menu',plain:true,
          // items: [
          //   {text:'批量导入课程',iconCls : 'icon-import',scope:this,handler:function(){this.importLesson()}}
          // ]}
        },'-',{
          text : '导出',iconCls : 'icon-export',
          handler : function() {
          this.exportLesson();
          }
        },'-',{
          text : '导出课程报表',iconCls : 'icon-export',
          handler : function() {
          this.exportLessonInfo();
          }
        },'-',{
          text : '导出课程学员报表',iconCls : 'icon-export',
          handler : function() {
          this.exportMember();
          }
        },'-',{
          text : '下载导入模版',iconCls : 'icon-export',
          handler : function() {
          this.exportLessonMode();
          }
        },'-',{
          xtype:'tbsplit',text: '查看课程', ref:'../../tvpView',iconCls : 'icon-updown',
          enableToggle: true, disabled : true,
          handler:function(){this.showLesson()},
          menu: {
          xtype:'menu',plain:true,
          items: [
            {text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
            {text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
            {text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
            {text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
            {text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hideLesson();Mt.Lesson.Config.View.IsShow=0;}},'-',
            {text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Lesson.Cookie.set('View.IsFix',Mt.Lesson.Config.View.IsFix);}}
          ]}
        },'-',
        {
        text : '选择会员',ref:'../../tmember',iconCls : 'icon-edit',disabled : true,
        handler : function() {
          if(Mt.Lesson.View.Running.selectMemberWindow==null || Mt.Lesson.View.Running.selectMemberWindow.hidden){
            this.showMember();
          }else{
            this.hideMember();
          }
        }
      },'-']}
      )]
    },
    bbar: new Ext.PagingToolbar({
      pageSize: Mt.Lesson.Config.PageSize,
      store: Mt.Lesson.Store.lessonStore,
      scope:this,autoShow:true,displayInfo: true,
      displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
      emptyMsg: "无显示数据",
      listeners:{
      change:function(thisbar,pagedata){
        if (Mt.Lesson.Viewport){
        if (Mt.Lesson.Config.View.IsShow==1){
          Mt.Lesson.View.IsSelectView=1;
        }
        this.ownerCt.hideLesson();
        Mt.Lesson.Config.View.IsShow=0;
        }
      }
      },
      items: [
      {xtype:'label', text: '每页显示'},
      {xtype:'numberfield', value:Mt.Lesson.Config.PageSize,minValue:1,width:35,
        style:'text-align:center',allowBlank: false,
        listeners:
        {
        change:function(Field, newValue, oldValue){
          var num = parseInt(newValue);
          if (isNaN(num) || !num || num<1)
          {
          num = Mt.Lesson.Config.PageSize;
          Field.setValue(num);
          }
          this.ownerCt.pageSize= num;
          Mt.Lesson.Config.PageSize = num;
          this.ownerCt.ownerCt.doSelectLesson();
        },
        specialKey :function(field,e){
          if (e.getKey() == Ext.EventObject.ENTER){
          var num = parseInt(field.getValue());
          if (isNaN(num) || !num || num<1)
          {
            num = Mt.Lesson.Config.PageSize;
          }
          this.ownerCt.pageSize= num;
          Mt.Lesson.Config.PageSize = num;
          this.ownerCt.ownerCt.doSelectLesson();
          }
        }
        }
      },
      {xtype:'label', text: '个'}
      ]
    })
    }, config);
    //初始化显示课程列表
    this.doSelectLesson();
    Mt.Lesson.View.Grid.superclass.constructor.call(this, config);
    //创建在Grid里显示的课程信息Tab页
    Mt.Lesson.View.Running.viewTabs=new Mt.Lesson.View.LessonView.Tabs();
    this.addListener('rowdblclick', this.onRowDoubleClick);
  },
  /**
   * 行选择器
   */
  sm : new Ext.grid.CheckboxSelectionModel({
    //handleMouseDown : Ext.emptyFn,
    listeners : {
    selectionchange:function(sm) {
      // 判断删除和更新按钮是否可以激活
      this.grid.btnRemove.setDisabled(sm.getCount() < 1);
      this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
      this.grid.tvpView.setDisabled(sm.getCount() != 1);
      this.grid.tmember.setDisabled(sm.getCount() < 1);
    },
    rowselect: function(sm, rowIndex, record) {
      if (sm.getCount() != 1){
      this.grid.hideLesson();
      Mt.Lesson.Config.View.IsShow=0;
      this.grid.hideMember(); 
      }else{
      if (Mt.Lesson.View.IsSelectView==1){
        Mt.Lesson.View.IsSelectView=0;
        this.grid.showLesson();
      }
      }
    },
    rowdeselect: function(sm, rowIndex, record) {
      if (sm.getCount() != 1){
      if (Mt.Lesson.Config.View.IsShow==1){
        Mt.Lesson.View.IsSelectView=1;
      }
      this.grid.hideLesson();
      Mt.Lesson.Config.View.IsShow=0;
      }
    }
    }
  }),
  /**
   * 双击选行
   */
  onRowDoubleClick:function(grid, rowIndex, e){
    if (!Mt.Lesson.Config.View.IsShow){
    this.sm.selectRow(rowIndex);
    this.showLesson();
    this.tvpView.toggle(true);
    }else{
    this.hideLesson();
    Mt.Lesson.Config.View.IsShow=0;
    this.sm.deselectRow(rowIndex);
    this.tvpView.toggle(false);
    }
  },
  /**
   * 是否绑定在本窗口上
   */
  onBindGrid:function(item, checked){
    if (checked){
     Mt.Lesson.Config.View.IsFix=1;
    }else{
     Mt.Lesson.Config.View.IsFix=0;
    }
    if (this.getSelectionModel().getSelected()==null){
    Mt.Lesson.Config.View.IsShow=0;
    return ;
    }
    if (Mt.Lesson.Config.View.IsShow==1){
     this.hideLesson();
     Mt.Lesson.Config.View.IsShow=0;
    }
    this.showLesson();
  },
  /**
   * 反选
   */
  onReverseSelect:function() {
    for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
    if (this.sm.isSelected(i)) {
      this.sm.deselectRow(i);
    }else {
      this.sm.selectRow(i, true);
    }
    }
  },
  /**
   * 查询符合条件的课程
   */
  doSelectLesson : function() {
    if (this.topToolbar){
        var llesson_name = this.topToolbar.llesson_name.getValue();
        this.filter     ={'lesson_name':llesson_name};
    }
    var condition = {'start':0,'limit':Mt.Lesson.Config.PageSize};
    Ext.apply(condition,this.filter);
    ExtServiceLesson.queryPageLesson(condition,function(provider, response) {
    if (response.result&&response.result.data) {
      var result       = new Array();
      result['data']     =response.result.data;
      result['totalCount'] =response.result.totalCount;
      Mt.Lesson.Store.lessonStore.loadData(result);
    } else {
      Mt.Lesson.Store.lessonStore.removeAll();
      Ext.Msg.alert('提示', '无符合条件的课程！');
    }
    });
  },
  /**
   * 显示课程视图
   * 显示课程的视图相对课程列表Grid的位置
   * 1:上方,2:下方,0:隐藏。
   */
  onUpDown:function(viewDirection){
    Mt.Lesson.Config.View.Direction=viewDirection;
    switch(viewDirection){
    case 1:
      this.ownerCt.north.add(Mt.Lesson.View.Running.viewTabs);
      break;
    case 2:
      this.ownerCt.south.add(Mt.Lesson.View.Running.viewTabs);
      break;
    case 3:
      this.ownerCt.west.add(Mt.Lesson.View.Running.viewTabs);
      break;
    case 4:
      this.ownerCt.east.add(Mt.Lesson.View.Running.viewTabs);
      break;
    }
    Mt.Lesson.Cookie.set('View.Direction',Mt.Lesson.Config.View.Direction);
    if (this.getSelectionModel().getSelected()!=null){
    if ((Mt.Lesson.Config.View.IsFix==0)&&(Mt.Lesson.Config.View.IsShow==1)){
      this.showLesson();
    }
    Mt.Lesson.Config.View.IsFix=1;
    Mt.Lesson.View.Running.lessonGrid.tvpView.menu.mBind.setChecked(true,true);
    Mt.Lesson.Config.View.IsShow=0;
    this.showLesson();
    }
  },
  /**
   * 显示课程
   */
  showLesson : function(){
    if (this.getSelectionModel().getSelected()==null){
    Ext.Msg.alert('提示', '请先选择课程！');
    Mt.Lesson.Config.View.IsShow=0;
    this.tvpView.toggle(false);
    return ;
    }
    if (Mt.Lesson.Config.View.IsFix==0){
    if (Mt.Lesson.View.Running.view_window==null){
      Mt.Lesson.View.Running.view_window=new Mt.Lesson.View.LessonView.Window();
    }
    if (Mt.Lesson.View.Running.view_window.hidden){
      Mt.Lesson.View.Running.view_window.show();
      Mt.Lesson.View.Running.view_window.winTabs.hideTabStripItem(Mt.Lesson.View.Running.view_window.winTabs.tabFix);
      this.updateViewLesson();
      this.tvpView.toggle(true);
      Mt.Lesson.Config.View.IsShow=1;
    }else{
      this.hideLesson();
      Mt.Lesson.Config.View.IsShow=0;
    }
    return;
    }
    switch(Mt.Lesson.Config.View.Direction){
    case 1:
      if (!this.ownerCt.north.items.contains(Mt.Lesson.View.Running.viewTabs)){
      this.ownerCt.north.add(Mt.Lesson.View.Running.viewTabs);
      }
      break;
    case 2:
      if (!this.ownerCt.south.items.contains(Mt.Lesson.View.Running.viewTabs)){
      this.ownerCt.south.add(Mt.Lesson.View.Running.viewTabs);
      }
      break;
    case 3:
      if (!this.ownerCt.west.items.contains(Mt.Lesson.View.Running.viewTabs)){
      this.ownerCt.west.add(Mt.Lesson.View.Running.viewTabs);
      }
      break;
    case 4:
      if (!this.ownerCt.east.items.contains(Mt.Lesson.View.Running.viewTabs)){
      this.ownerCt.east.add(Mt.Lesson.View.Running.viewTabs);
      }
      break;
    }
    this.hideLesson();
    if (Mt.Lesson.Config.View.IsShow==0){
    Mt.Lesson.View.Running.viewTabs.enableCollapse();
    switch(Mt.Lesson.Config.View.Direction){
      case 1:
      this.ownerCt.north.show();
      break;
      case 2:
      this.ownerCt.south.show();
      break;
      case 3:
      this.ownerCt.west.show();
      break;
      case 4:
      this.ownerCt.east.show();
      break;
    }
    this.updateViewLesson();
    this.tvpView.toggle(true);
    Mt.Lesson.Config.View.IsShow=1;
    }else{
    Mt.Lesson.Config.View.IsShow=0;
    }
    this.ownerCt.doLayout();
  },
  /**
   * 隐藏课程
   */
  hideLesson : function(){
    this.ownerCt.north.hide();
    this.ownerCt.south.hide();
    this.ownerCt.west.hide();
    this.ownerCt.east.hide();
    if (Mt.Lesson.View.Running.view_window!=null){
    Mt.Lesson.View.Running.view_window.hide();
    }
    this.tvpView.toggle(false);
    this.ownerCt.doLayout();
  },
  /**
   * 更新当前课程显示信息
   */
  updateViewLesson : function() {
      Mt.Lesson.View.Running.mlessonGrid.doSelectMlesson();
      Mt.Lesson.View.Running.chapterGrid.doSelectChapter();
    if (Mt.Lesson.View.Running.view_window!=null){
    Mt.Lesson.View.Running.view_window.winTabs.tabLessonDetail.update(this.getSelectionModel().getSelected().data);
    }
    Mt.Lesson.View.Running.viewTabs.tabLessonDetail.update(this.getSelectionModel().getSelected().data);
  },
  /**
   * 新建课程
   */
  addLesson : function() {
    if (Mt.Lesson.View.Running.edit_window==null){
    Mt.Lesson.View.Running.edit_window=new Mt.Lesson.View.EditWindow();
    }
    Mt.Lesson.View.Running.edit_window.resetBtn.setVisible(false);
    Mt.Lesson.View.Running.edit_window.saveBtn.setText('保 存');
    Mt.Lesson.View.Running.edit_window.setTitle('添加课程');
    Mt.Lesson.View.Running.edit_window.savetype=0;
    Mt.Lesson.View.Running.edit_window.lesson_id.setValue("");
    Mt.Lesson.View.Running.edit_window.head_imageUpload.setValue("");
    Mt.Lesson.View.Running.edit_window.show();
    Mt.Lesson.View.Running.edit_window.maximize();
  },
  /**
   * 编辑课程时先获得选中的课程信息
   */
  updateLesson : function() {
    if (Mt.Lesson.View.Running.edit_window==null){
    Mt.Lesson.View.Running.edit_window=new Mt.Lesson.View.EditWindow();
    }
    Mt.Lesson.View.Running.edit_window.saveBtn.setText('修 改');
    Mt.Lesson.View.Running.edit_window.resetBtn.setVisible(true);
    Mt.Lesson.View.Running.edit_window.setTitle('修改课程');
    Mt.Lesson.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
    Mt.Lesson.View.Running.edit_window.savetype=1;
    Mt.Lesson.View.Running.edit_window.head_imageUpload.setValue(Mt.Lesson.View.Running.edit_window.head_image.getValue());
    Mt.Lesson.View.Running.edit_window.show();
    Mt.Lesson.View.Running.edit_window.maximize();
  },
  /**
   * 删除课程
   */
  deleteLesson : function() {
    Ext.Msg.confirm('提示', '确实要删除所选的课程吗?', this.confirmDeleteLesson,this);
  },
  /**
   * 确认删除课程
   */
  confirmDeleteLesson : function(btn) {
    if (btn == 'yes') {
    var del_lesson_ids ="";
    var selectedRows  = this.getSelectionModel().getSelections();
    for ( var flag = 0; flag < selectedRows.length; flag++) {
      del_lesson_ids=del_lesson_ids+selectedRows[flag].data.lesson_id+",";
    }
    ExtServiceLesson.deleteByIds(del_lesson_ids);
    this.doSelectLesson();
    Ext.Msg.alert("提示", "删除成功！");
    }
  },
    /**
     * 显示会员
     */
    showMember:function(){
      if (Mt.Lesson.View.Running.selectMemberWindow==null){
        Mt.Lesson.View.Running.selectMemberWindow=new Mt.Lesson.View.MemberView.SelectMemberWindow();
      }

      var ret = {};
      var selectedRows  = Mt.Lesson.View.Running.lessonGrid.getSelectionModel().getSelections();

      if (selectedRows.length == 1) {
        ret = this.selOneLesson(selectedRows);
      }else{
        ret = this.selManyLesson(selectedRows);
      }

      var selMemberWin   = Mt.Lesson.View.Running.selectMemberWindow;
      var selMemberGrid  = selMemberWin.memberGrid;

      selMemberWin.selData = ret.selData;
      selMemberWin.oldData = ret.oldData;
      selMemberGrid.lesson_id = ret.lesson_id;

      selMemberWin.changeTitle(); 
      
      if (selMemberWin.hidden){ 
        Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.mdepartment_id.setValue("");
        Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.mposition_id.setValue("");
        Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.marea_id.setValue("");
        Mt.Lesson.View.Running.selectMemberWindow.memberGrid.topToolbar.musername.setValue("");
        selMemberGrid.filter = {selMember:ret.memberStr};
        selMemberGrid.topToolbar.menus.all.setChecked(true);
        selMemberGrid.isSelect.toggle(false);
        Mt.Lesson.Store.selectMemberStore.removeAll();
      }
      selMemberGrid.doSelectMember();
      selMemberWin.show();

    },

    //选择复数的会员
    selManyLesson:function(selectedRows){
      var lesson_ids = new Array();
      for (var i = selectedRows.length - 1; i >= 0; i--) {
        lesson_ids.push(selectedRows[i].data.lesson_id);
      }
      
      return {lesson_id:lesson_ids, memberStr:'', selData:{}, oldData:{}}; 
    },
    
    //选择一个会员
    selOneLesson:function(selectedRows){
      //关联会员ID组成的字符串
      var lesson_id = selectedRows[0].data.lesson_id;
      var memberStr  = selectedRows[0].data.memberStr;
    
      var selData  = {};
      var oldData  = {};
      if(memberStr){
        var memberArr = memberStr.split(",");
        for(var i=0;i<memberArr.length;i++){
          selData[memberArr[i]] = true;//ture为已存在的关联货品
          oldData[memberArr[i]] = {};
          oldData[memberArr[i]].active = true;
        }
      }

      return {lesson_id:[lesson_id], memberStr:memberStr, selData:selData, oldData:oldData};
    },
    /**
     * 隐藏会员
     */
    hideMember:function(){
      if (Mt.Lesson.View.Running.selectMemberWindow!=null){
        Mt.Lesson.View.Running.selectMemberWindow.hide();
      }
    },
  /**
   * 导出课程
   */
  exportLesson : function() {
    var lesson_ids ="";
    var selectedRows  = this.getSelectionModel().getSelections();
    for ( var flag = 0; flag < selectedRows.length; flag++) {
      lesson_ids=lesson_ids+selectedRows[flag].data.lesson_id+",";
    }
    var condition = {'lesson_ids':lesson_ids};
    Ext.apply(condition,this.filter);
    ExtServiceLesson.exportLesson(condition,function(provider, response) {
    if (response.result.data) {
      window.open(response.result.data);
    }
    });
  },
  /**
   * 导出课程报表
   */
  exportLessonInfo : function() {
    ExtServiceLesson.exportLessonInfo(this.filter,function(provider, response) {
    if (response.result.data) {
      window.open(response.result.data);
    }
    });
  },
  /**
   * 导出课程学员报表
   */
  exportMember : function() {
    ExtServiceLesson.exportMember(this.filter,function(provider, response) {
      if (response.result.data) {
        window.open(response.result.data);
      }
    });
  },
  /**
   * 下载导入模版
   */
  exportLessonMode : function() {
    window.open("attachment/lesson/lesson.xls");
  },
  /**
   * 导入课程
   */
  importLesson : function() {
    if (Mt.Lesson.View.current_uploadWindow==null){
    Mt.Lesson.View.current_uploadWindow=new Mt.Lesson.View.UploadWindow();
    }
    Mt.Lesson.View.current_uploadWindow.show();
  }
  }),
  /**
   * 核心内容区
   */
  Panel:Ext.extend(Ext.form.FormPanel,{
  constructor : function(config) {
    Mt.Lesson.View.Running.lessonGrid=new Mt.Lesson.View.Grid();
    if (Mt.Lesson.Config.View.IsFix==0){
    Mt.Lesson.View.Running.lessonGrid.tvpView.menu.mBind.setChecked(false,true);
    }
    config = Ext.apply({
    region : 'center',layout : 'fit', frame:true,
    items: {
      layout:'border',
      items:[
      Mt.Lesson.View.Running.lessonGrid,
      {region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
      {region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Lesson.View.Running.viewTabs]},
      {region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
      {region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
      ]
    }
    }, config);
    Mt.Lesson.View.Panel.superclass.constructor.call(this, config);
  }
  }),
  /**
   * 当前运行的可视化对象
   */
  Running:{
  /**
   * 当前课程Grid对象
   */
  lessonGrid:null,
    /**
     * 当前会员课程Grid对象
     */
    mlessonGrid:null,
    /**
     * 当前章节Grid对象
     */
    chapterGrid:null,
    /**
     * 推荐会员
     */
    selectMemberWindow:null,
  /**
   * 显示课程信息及关联信息列表的Tab页
   */
  viewTabs:null,
  /**
   * 当前创建的编辑窗口
   */
  edit_window:null,
  /**
   * 当前的显示窗口
   */
  view_window:null
  }
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
  Ext.QuickTips.init();
  Ext.state.Manager.setProvider(Mt.Lesson.Cookie);
  Ext.Direct.addProvider(Ext.app.REMOTING_API);
  Mt.Lesson.Init();
  /**
   * 课程数据模型获取数据Direct调用
   */
  Mt.Lesson.Store.lessonStore.proxy=new Ext.data.DirectProxy({
  api: {read:ExtServiceLesson.queryPageLesson}
  });
  /**
   * 课程页面布局
   */
  Mt.Lesson.Viewport = new Ext.Viewport({
  layout : 'border',
  items : [new Mt.Lesson.View.Panel()]
  });
  Mt.Lesson.Viewport.doLayout();
  setTimeout(function(){
  Ext.get('loading').remove();
  Ext.get('loading-mask').fadeOut({
    remove:true
  });
  }, 250);
});